package piblanes;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.HashSet;
import java.util.Map;
import javax.swing.Timer;

/**
 *
 */

public class KeyboardController extends Controller {
    public KeyboardController(Player player_, Map<Integer, ControllerSignal> buttonAction_) {
        super(player_);
        this.buttonAction = buttonAction_;
    }

    public KeyHandler getKeyHandler()
    {
        return handler;
    }

    public class KeyHandler extends KeyAdapter {
        public KeyHandler() {
            keyTimer = new Timer(20, new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    for (Integer keyCode : pressedKeys) {
                        if (buttonAction.containsKey(keyCode))
                            player.receiveSignal(buttonAction.get(keyCode));
                    }
                }
            });
            keyTimer.start();
        }

        @Override
        public void keyPressed(KeyEvent event) {
          //  System.out.println("Anything");
            pressedKeys.add(event.getKeyCode());
        }

        @Override
        public void keyReleased(KeyEvent event) {
            pressedKeys.remove(event.getKeyCode());
        }

        private HashSet<Integer> pressedKeys = new HashSet<Integer>();
        private Timer keyTimer;
    }
    
    private Map <Integer, ControllerSignal> buttonAction;
    private KeyHandler handler = new KeyHandler();
}
